package ctrl

import cn.xnatural.app.ServerTpl
import cn.xnatural.app.util.DB
import cn.xnatural.enet.event.EL
import cn.xnatural.http.ApiResp.ok
import cn.xnatural.http._

import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.ConcurrentHashMap
import scala.jdk.javaapi.CollectionConverters

@Ctrl(prefix = "test")
class TestCtrl extends ServerTpl {
  lazy val wss = ConcurrentHashMap.newKeySet[WebSocket]()
  lazy val repo = bean(classOf[DB])
  // lazy val fu   = bean(classOf[FileUploader])

  @Filter(order = 1)
  def filter1(): Unit = {
    log.info("test filter1 ============")
  }

  @Filter(order = 0)
  def filter2(hCtx: HttpContext): Unit = {
    // log.info('test filter2 ============')
  }


  @EL(name = Array("testWsMsg"))
  def wsMsgBroadcast(msg: String): Unit = {
    wss.forEach(_.send(msg))
  }


  @WS(path = "msg")
  def wsMsg(ws: WebSocket): Unit = {
    log.info("WS connect. {}", ws.getSession.getRemoteAddress)
    ws.listen(new WsListener() {
      override
      def onClose(wst: WebSocket): Unit = wss.remove(wst)
      override
      def onText(msg: String): Unit = {
        log.info("test ws receive client msg: {}", msg)
      }
    })
    wsMsgBroadcast("上线: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
    wss.add(ws)
  }

  
  // 测试抛出错误
  @Path(path = Array("error"), produce = "application/json")
  def error(): Any = {
    throw new Exception("错误测试")
  }


  // dao 测试
  @Path(path = Array("dao"))
  def dao(): Any = {
    ApiResp.ok(repo.single("select count(1) from test", classOf[java.lang.Long]))
  }


  // 接收form 表单提交
  @Path(path = Array("form"), consumer = Array("application/x-www-form-urlencoded"))
  def form(p1: Int, hCtx: HttpContext): Any = {
    ApiResp.ok(hCtx.request.getFormParams)
  }


  // json 参数
  @Path(path = Array("json"), consumer = Array("application/json"))
  def json(p1: String, hCtx: HttpContext): Any =  {
    ApiResp.ok(hCtx.request.getJsonParams)
  }


  // 接收post string
  @Path(path = Array("string"))
  def string(hCtx: HttpContext): Any = {
    ApiResp.ok(hCtx.request.getBodyStr)
  }


  // 文件上传
  @Path(path = Array("upload"))
  def upload(file: FileData, version: String): Any = {
    if (file == null) return ApiResp.fail("文件未上传")
    // fu.save(file)
    // repo.execute("insert into version_file(version, origin_name, final_name, comment) values(?, ?, ?, ?)", "1.2.3", "test.txt", "abcdf.txt", "")
    // ok(fu.toFullUrl(file.finalName))
    ApiResp.ok()
  }


  // 自定义接口
  @Path(path = Array("cus"))
  def cus(p1: String): Any = {
    ApiResp.ok(s"p1: ${p1} ${new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date)}")
  }
}
